<template>
  <scroll class="suggest" :beforeScroll="beforeScroll" @beforeScroll="beforeScrollStart" :data="result" :pullup="pullup" @pullingUp="handlePullingUp" ref="refScroll">
    <ul class="suggest-list">
      <li class="suggest-item" @click="seletItem(item)" v-for="(item, index) in result" :key="index">
        <div class="icon">
          <i :class="getIconCls(item)"></i>
        </div>
        <div class="name">
          <p class="text" v-html="getDisplayName(item)"></p>
        </div>
      </li>
      <li>
        <div class="loading-wrapper">
          <loading v-show="isLoading" title=""></loading>
        </div>
      </li>
    </ul>
    <div class="no-result-wrapper" v-show="!hasMore && !result.length">
      <no-result title="抱歉，暂无搜索结果"></no-result>
    </div>
  </scroll>
</template>

<script type="text/ecmascript-6">
  import Scroll from 'base/scroll/scroll'
  import Loading from 'base/loading/loading'
  import { search } from 'api/search'
  import { ERR_OK } from 'api/config'
  import { createSong } from 'common/js/song'
  import Singer from 'common/js/singer'
  import { mapMutations, mapActions } from 'vuex'
  import noResult from 'base/no-result/no-result'

  const TYPE_SINGER = 'singer'
  const PAGE_SIZE = 20

  export default {
    name: 'suggest',
    props: {
      query: {
        type: String,
        defalut: ''
      },
      searchSinger: {
        type: Boolean,
        defalut: true
      }
    },
    components: {
      Scroll,
      Loading,
      noResult
    },
    data() {
      return {
        page: 1,
        result: [],
        pullup: true,
        hasMore: true, // 表示是否还有更多的下拉数据
        isLoading: false, // 表示正在加载下拉数据
        beforeScroll: true
      }
    },
    methods: {
      refresh() {
        this.$refs.refScroll.refresh()
      },
      beforeScrollStart() {
        this.$emit('beforeScrollStart')
      },
      seletItem(item) {
        if (item.type === TYPE_SINGER) {
          const singer = new Singer('', item.singerid, item.singermid, item.singername, '', '')
          this.$router.push({
            path: `/search/${singer.id}`
          })
          this.setSinger(singer)
        } else {
          this.insertSong(item)
        }
        this.$emit('select', item)
      },
      handlePullingUp() {
        this._searchMore()
      },
      getIconCls(item) {
        if (item.type === TYPE_SINGER) {
          return 'icon-mine'
        } else {
          return 'icon-music'
        }
      },
      getDisplayName(item) {
        if (item.type === TYPE_SINGER) {
          return item.singername
        } else {
          return `${item.name}-${item.singer}`
        }
      },
      _genResult(data) {
        let ret = []
        if (data.zhida && data.zhida.singermid && this.page <= 1) {
          ret.push({
            ...data.zhida,
            type: TYPE_SINGER
          })
        }
        if (data.song && data.song.list) {
          ret = ret.concat(this._normalizSong(data.song.list))
        }
        return ret
      },
      _normalizSong(list) {
        let arr = []
        list.forEach((item) => {
          if (item.songmid) {
            arr.push(createSong(item))
          }
        })
        return arr
      },
      _searchMore() {
        if (!this.hasMore) return
        if (this.isLoading) return
        this.isLoading = true
        this.page = this.page + 1
        search(this.query, this.page, this.searchSinger, PAGE_SIZE).then((resp) => {
          if (resp.code === ERR_OK) {
            this.result = this.result.concat(this._genResult(resp.data))
            this._checkHasMore(resp.data)
          }
          this.isLoading = false
        }).catch(() => {
          this.isLoading = false
        })
      },
      _checkHasMore(data) {
        // curnum: 20
        // curpage: 1
        // totalnum: 400
        if (!data.song || data.song.length <= 0) {
          this.hasMore = false
          return
        }
        if ((data.song.curnum + data.song.curpage * PAGE_SIZE) > data.song.totalnum) {
          this.hasMore = false
          return
        }
        this.hasMore = true
      },
      ...mapMutations({
        setSinger: 'SET_SINGER'
      }),
      ...mapActions({
        insertSong: 'insertSong'
      })
    },
    created() {
    },
    watch: {
      query(newVal) {
        this.page = 1
        this.hasMore = true
        search(newVal, this.page, this.searchSinger, PAGE_SIZE).then((resp) => {
          if (this.isLoading) return
          this.isLoading = true
          if (resp.code === ERR_OK) {
            this.result = this._genResult(resp.data)
            this._checkHasMore(resp.data)
            this.refs.refScroll.scrollTo(0, 0)
          }
          this.isLoading = false
        }).catch(() => {
          this.isLoading = false
        })
      }
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus" scoped>
  @import '~common/stylus/variable'
  @import '~common/stylus/mixin'

  .suggest
    height: 100%
    overflow: hidden
    .suggest-list
      padding: 0 30px 30px 30px
      .suggest-item
        display: flex
        height: 30px
        align-items: center
        padding-bottom: 10px
        .icon
          flex: 0 0 30px
          width: 30px
          /* eslint-disable */
          [class^="icon-"]
            font-size: 14px
            color: $color-text-d
        .name
          flex: 1
          font-size: $font-size-medium
          color: $color-text-d
          overflow: hidden
          .text
            no-wrap()

      .loading-wrapper
        width: 100%
    .no-result-wrapper
      position: absolute
      width: 100%
      top: 50%
      transform: translateY(-50%)
</style>
